<?php

class ConfigurationManager
{
	const filename = "config/config.php";

	private $store;

	function load()
	{
		require_once(self::filename);
		$this->store = $_CONFIG;
	}

	function save()
	{
		$f = fopen(self::filename, 'w');
		fwrite($f, '<?php' . "\n");

		foreach($this->store as $key => $value)
		{
			// Write in format $_CONFIG[key] = val;
			fwrite($f, '$_CONFIG[\'' 
					. $key 
					. '\'] = ');

			if(is_bool($value))
			{
				fwrite($f, $value ? 'true' : 'false');
			}
			else if (is_int($value) || is_float($value))
			{
				fwrite($f, $value);
			}
			else if(is_string($value))
			{
				// Replace all \ with \\ and then all ' with 
				// \' so there won't be escaping problems
				fwrite($f, '\'' 
					. str_replace("'", "\\'",str_replace("\\", "\\\\", $value))
				       	. '\'');
			}
			else
			{
				throw new Exception("Only bools, ints, floats & strings allowed in config files");
			}

			fwrite($f, ";\n");
		}
		fwrite($f, '?>' . "\n");
		fclose($f);
	}

	function __set($key, $value)
	{
		$this->store[$key] = $value;
	}

	function __get($key)
	{
		return $this->store[$key];
	}
}

?>
